package unei.net.nio;

import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Created by sunlei on 2015/8/31.
 */
public class NioTransport {

    private NioServer nioServer;
    private Socket socket;
    private SelectorSelection selectorSelection;
    private ByteBuffer buffer=ByteBuffer.allocate(8*1024);

    public NioTransport(SelectorSelection selectorSelection,Socket socket){
        this.selectorSelection=selectorSelection;
        this.socket=socket;
    }

    public void receive(){
        SocketChannel channel=socket.getChannel();
       buffer.clear();
        try{
            byte[] bytes=new byte[8*1024];
                int readSize=channel.read(buffer);
                if(readSize==-1){
                    selectorSelection.close();
                    throw new EOFException();
                }

            buffer.flip();

            if(readSize>0){
                buffer.get(bytes,0,buffer.remaining());

                String cmd=new String(bytes);
                nioServer.doReceive(this,cmd);
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void send(String data){
        System.out.println("send:"+data);
        SocketChannel channel=socket.getChannel();
        buffer.clear();

        try {
            buffer.put(data.getBytes());
            channel.write(buffer);
            buffer.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setNioServer(NioServer nioServer) {
        this.nioServer = nioServer;
    }

    public NioServer getNioServer() {
        return nioServer;
    }

    public Socket getSocket() {
        return socket;
    }

    public SelectorSelection getSelectorSelection() {
        return selectorSelection;
    }
}
